const Router = require('koa-router')
const ApiRes = require('../../lib/utils/api-res')
const router = new Router({ prefix: '/route' })
const RouteService = require('../../services/route')

const validator = require('../../middleware/validator')
const Joi = require('joi')

const RouteController = require('../../controller/route')

router.get('/getConstantRoutes', async (ctx, next) => {
  const routes = await RouteService.findConstRoutes()
  ctx.body = ApiRes.success(routes)
})

router.get('/getAllPages', RouteController.getAllPages)

router.get('/getMenuTree', RouteController.getRouteMenuTree)

router.get('/',  RouteController.findAllRoute)

router.get('/:id', RouteController.findRouteById)

router.post(
  '/',
  validator({
    menu_type: Joi.string().valid('directory', 'menu').required(),
    menu_name: Joi.string().max(64).required(),
    icon_type: Joi.number().default(1),
    icon: Joi.string().max(64).allow(''),
    route_name: Joi.string().max(64).required(),
    route_path: Joi.string().max(128).required(),
    component: Joi.string().max(64).allow(''),
    path_param: Joi.string().max(64),
    status: Joi.string().valid('ENABLED', 'DISABLED', 'BANNED').default('ENABLED'),
    active_menu: Joi.string().max(64).allow(null),
    hide_in_menu: Joi.boolean().default(false),
    pid: Joi.number().default(0),
    sequence: Joi.number().default(0),
    i18n_key: Joi.string().max(64),
    keep_alive: Joi.boolean().default(false),
    constant: Joi.boolean().default(false),
    href: Joi.string().max(64).allow(null),
    multi_tab: Joi.boolean().default(false),
    fixed_index_in_tab: Joi.number().allow(null).default(0),
    buttons: Joi.array().default([]),
    query: Joi.array().default([]),
    created_by: Joi.string().default('-1'),
  }),
  RouteController.createRoute
)

router.put(
  '/:id',
  validator({
    id: Joi.number().required(),
    menu_type: Joi.string().valid('directory', 'menu'),
    menu_name: Joi.string().max(64),
    icon_type: Joi.number(),
    icon: Joi.string().max(64).allow(''),
    route_name: Joi.string().max(64),
    route_path: Joi.string().max(128),
    component: Joi.string().max(64).allow(''),
    path_param: Joi.string().max(64),
    status: Joi.string().valid('ENABLED', 'DISABLED', 'BANNED'),
    active_menu: Joi.string().max(64).allow(null),
    hide_in_menu: Joi.boolean(),
    pid: Joi.number().default(0),
    sequence: Joi.number().default(0),
    i18n_key: Joi.string().max(64),
    keep_alive: Joi.boolean(),
    constant: Joi.boolean(),
    href: Joi.string().max(64).allow(null),
    multi_tab: Joi.boolean(),
    fixed_index_in_tab: Joi.number().allow(null),
    buttons: Joi.array(),
    query: Joi.array()
  }),
  RouteController.updateRoute
)

router.delete('/:id', RouteController.deleteRoute)

router.get('/auth-route/:roleCode', RouteController.getRoteIdsByRoleCode)

module.exports = router
